﻿using Minecraft.BLL;
using Minecraft.BLL.mysql;
using Minecraft.CacheRedis;
using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Model;
using Minecraft.Model.Backpack;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Minecraft.InitTest
{
	public class Init
	{
		private static RedisCacheHelper redisCacheHelper = new RedisCacheHelper();
		private static int playerNum = 50; //模拟玩家个数
		private static string FurnitureItemId = "144000";
		/// <summary>
		/// 执行初始化方法
		/// </summary>
		public static void Do()
		{
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			Console.WriteLine("正在初始化数据...");
			CsvConfig.Install();
			redisCacheHelper.FlushAll();

			TruncateTables();
			InitSubmeter();

			var furnitureList = InitFurniture(9);

			InitSurvivor();
			InitPlayerbasis();

			//GoodsInit(new List<int> { 1, 9 }, furnitureList);

			InitMap();

			InitAchievements();

			stopwatch.Stop();

			Console.WriteLine($"数据初始化完成，所花时间为：{stopwatch.Elapsed.TotalSeconds.ToString("0.00")} s");
		}
		/// <summary>
		/// 初始化一般表数据
		/// </summary>
		private static void TruncateTables()
		{
			BaseBLL.TruncateTable(new PlayerbasisModel());
			BaseBLL.TruncateTable(new FurnitureModel());
			BaseBLL.TruncateTable(new BlueprintModel());
			BaseBLL.TruncateTable(new MapModel());
			BaseBLL.TruncateTable(new SurvivorModel());
			BaseBLL.TruncateTable(new AchievementModel());
		}
		/// <summary>
		/// 初始化分表数据
		/// </summary>
		private static void InitSubmeter()
		{
			BaseBLL.DropTablesWithPrefix(TablePrefixKey.Goods);
			BaseBLL.DropTablesWithPrefix(TablePrefixKey.Friend);
		}

		public static void InitSurvivor()
		{
			var list = new List<SurvivorModel>();
			for (int i = 1; i <= playerNum; i++)
			{
				SurvivorModel model = new SurvivorModel()
				{
					PlayerId = i,
					CreateTime = DateTimeOffset.Now.AddSeconds(-i),
					SurvivorId = 1,
					State = (int)EnumSurvivorState.InIdle,
				};
				list.Add(model);
			}
			BaseBLL.BatchInsert(list);
		}

		public static void InitMap()
		{
			var list = new List<MapModel>();
			for (int i = 1; i <= playerNum; i++)
			{
				MapModel model = new MapModel()
				{
					PlayerId = i,
					SourceMapId = MinecraftConfig.BaseMapId,
					TargetMapId = "",
					TimeTicks = "",
					UnlockedDepotIds = string.Join("|", MinecraftConfig.BaseMapId),
					LastMapId = "",
				};
				list.Add(model);
			}
			BaseBLL.BatchInsert(list);
		}

		/// <summary>
		/// 家具表的数据初始化
		/// </summary>
		public static List<FurnitureModel> InitFurniture(int playerId)
		{
			var list = new List<FurnitureModel>();

			for (int i = 1; i <= playerNum; i++)
			{
				string furnitureItemId = FurnitureItemId;
				if (i == playerId)
				{
					furnitureItemId = "140000";
				}
				//Mod_Furniture mod_Furniture = CsvConfig.furnitureList.FirstOrDefault(m => m.Id == furnitureItemId);
				Mod_Drawing mod_Drawing = CsvConfig.GetMod_DrawingInfoById(furnitureItemId);
				FurnitureModel model = new FurnitureModel()
				{
					FurnitureId = 1.ToString(),
					FurnitureItemId = furnitureItemId,
					FurnitureTypeId = (int)mod_Drawing.enumFurnitureType_Convert,
					PlayerId = i,
					Point_X = 16,
					Point_Y = 16,
					Point_Z = 16,
					angle = 0,
					Level = 1,
					Hp = MinecraftConfig.PlayerInitHp,
					Output_MaterialGoodsItemIdsPosAndNums = "",
					Output_ResultGoodsItemId = "",
					Output_ResultGoodsNum = 0,
					Output_timeTicksStr = "",
					Upgrade_MaterialGoodsItemIdsAndNums = "",
					Upgrade_StartTime = DateTimeOffset.Now,
					Upgrade_State = 0,
					TreasureBox_MapId = "",
					TreasureBox_IsPrefab = 0,
					Repair_MaterialGoodsItemIdsAndNums = "",
					Repair_StartTime = DateTimeOffset.Now,
					Repair_State = 0,

				};
				list.Add(model);
			}
			BaseBLL.BatchInsert(list);
			return list;
		}

		/// <summary>
		/// 初始化player基础数据
		/// </summary>
		private static void InitPlayerbasis()
		{
			List<PlayerbasisModel> list = new List<PlayerbasisModel>();
			for (int i = 1; i <= playerNum; i++)
			{
				//插入一条数据
				PlayerbasisModel model = new PlayerbasisModel
				{
					PlayerId = i,
					IsLoggedIn = 0,
					LastLoginTime = DateTimeOffset.Now,
					LastLogoutTime = DateTimeOffset.Now,
					Name = $"Player_{i}",
					PhysicalStrengthValue = MinecraftConfig.PhysicalStrengthUpperLimit,
					Fight_Attack = MinecraftConfig.PlayerInitAtk,
					Exp = 5,
					Fight_AttackSpeed = MinecraftConfig.PlayerInitAtkSpeed,
					Fight_Defense = MinecraftConfig.PlayerInitDefense,
					Fight_TravelRate = MinecraftConfig.PlayerInitMoveSpeed,
					GoldCoin = 0,
					Human_Clean = MinecraftConfig.PlayerInitClear,
					Human_GoToilet = 0,
					Human_Hunger = MinecraftConfig.PlayerInitHunger,
					Human_Life = MinecraftConfig.PlayerInitHp,
					SkillPoint = 10,
					PhysicalStrengthLastGrowTime = DateTimeOffset.Now,
					ShortcutBarWeaponPos = 0,
				};
				list.Add(model);
			}

			BaseBLL.BatchInsert(list);
		}



		/// <summary>
		/// 初始化朋友表数据
		/// </summary>
		public static void InsertFriendData()
		{
			var friendTableNameCacheList = new List<string>();

			for (int i = 1; i <= 10; i++)
			{
				for (int j = 1; j <= 10; j++)
				{
					var friendModel = new FriendModel()
					{
						PlayerId = i + 9995,
						FriendId = j,
						AddTime = DateTimeOffset.Now
					};
					FriendBLL.InsertSuccessForSplitTable(friendModel, friendTableNameCacheList);
					friendModel = new FriendModel()
					{
						PlayerId = j,
						FriendId = i + 9995,
						AddTime = DateTimeOffset.Now
					};
					FriendBLL.InsertSuccessForSplitTable(friendModel, friendTableNameCacheList);
				}
			}
		}

		public static void InitBackpack()
		{
			for (int p = 1; p <= playerNum; p++)
			{
				List<GoodsModel> goodsList = new List<GoodsModel>();
				BackpackShortcutBarInit(goodsList, p, MinecraftConfig.ShortcutBarCellInitNum, EnumGoodsBelongsToType.ShortcutBar);
				BackpackShortcutBarInit(goodsList, p, MinecraftConfig.BackpackCellInitNum, EnumGoodsBelongsToType.Backpack);
				GoodsBLL.BatchUpdateWithTablePrefix(goodsList, MemorySystemManager.goodsTableNameCacheList, p, true);
			}
		}

		/// <summary>
		/// 初始化物品
		/// </summary>
		/// <param name="backpackGoodsNum"></param>
		/// <param name="playerId"></param>
		public static void GoodsInit(List<int> playerIdList, List<FurnitureModel> furnitureList)
		{
			//var itemsList = CsvConfig.itemsList.Where(m => m.Type_Convert > -1).ToList();
			//var itemsList = CsvConfig.GetitemsDict().Select(m => m.Value).Where(m => m.Type_Convert > -1).ToList();
			var itemsList = CsvConfig.GetitemsDict().Select(m => m.Value).ToList();
			int backpackGoodsNum = 1;// Math.Min(MinecraftConfig.BackpackCellInitNum, itemsList.Count());
			for (int p = 1; p <= playerNum; p++)
			{
				List<GoodsModel> goodsList = new List<GoodsModel>();

				for (int i = 0; i < backpackGoodsNum; i++)
				{
					Random random2 = new Random(DateTimeHelper.GetTotalSecondsIntOfThisYear() + i);
					var goodsItemId2 = itemsList[i].Id;
					string guid = "";
					if (playerIdList.Any(m => m == p))
					{
						var half = backpackGoodsNum / 5;
						if (i < half)
						{
							goodsItemId2 = "140001";
						}
						else if (i < half * 2)
						{
							goodsItemId2 = "100000";
						}
						else if (i < half * 3)
						{
							goodsItemId2 = "100002";
						}
						else if (i < half * 4)
						{
							goodsItemId2 = "100004";
						}
						else
						{
							goodsItemId2 = "100006";
						}
					}

					var maxNum2 = itemsList.FirstOrDefault(m => m.Id == goodsItemId2).Max_num_Convert * 5;
					GoodsModel goodsModel = new GoodsModel
					{
						GoodsId = StringHelper.GetGuidStr(),
						BelongsTo = (int)EnumGoodsBelongsToType.Backpack,
						GoodsItemId = goodsItemId2,
						PlayerId = p,
						GoodsPosition = i,
						WastageValue = 100,
						guid = guid,
						Num = maxNum2
					};
					goodsList.Add(goodsModel);
				}
				if (p == 5)
				{
					var position = backpackGoodsNum;
					GoodsModel goodsModel2 = new GoodsModel
					{
						GoodsId = StringHelper.GetGuidStr(),
						BelongsTo = (int)EnumGoodsBelongsToType.Backpack,
						GoodsItemId = "255",
						PlayerId = p,
						GoodsPosition = position,
						WastageValue = 100,
						guid = "",
						Num = 10
					};
					goodsList.Add(goodsModel2);
				}
				GoodsBLL.BatchUpdateWithTablePrefix(goodsList, MemorySystemManager.goodsTableNameCacheList, p, true);
			}
		}

		public static void BackpackShortcutBarInit(List<GoodsModel> goodsList,
			int playerId, int cellNum,
			EnumGoodsBelongsToType enumGoodsBelongsToType)
		{
			//var itemsList = CsvConfig.itemsList.Where(m => m.Type_Convert > -1).ToList();
			//var itemsList = CsvConfig.GetitemsDict().Select(m => m.Value).Where(m => m.Type_Convert > -1).ToList();
			var itemsList = CsvConfig.GetitemsDict().Select(m => m.Value).ToList();
			List<BackpackGoodsItemInfo> itemList = new List<BackpackGoodsItemInfo>();
			//写死一个家具，放在背包中的位置0处
			BackpackGoodsItemInfo furnitureItem2 = new BackpackGoodsItemInfo
			{
				enumGoodsBelongsToType = enumGoodsBelongsToType,
				GoodsPosition = 0,
				GoodsItemId = FurnitureItemId,
				GoodsNum = 1,
			};
			itemList.Add(furnitureItem2);
			for (int i = 1; i < cellNum; i++)
			{
				Random random = new Random(DateTimeHelper.GetTotalSecondsIntOfThisYear() + i);
				var goodsItemId = itemsList[random.Next(itemsList.Count())].Id;
				var maxNum = itemsList.FirstOrDefault(m => m.Id == goodsItemId).Max_num_Convert;
				BackpackGoodsItemInfo backpackItem = new BackpackGoodsItemInfo
				{
					enumGoodsBelongsToType = enumGoodsBelongsToType,
					GoodsPosition = i,
					GoodsItemId = goodsItemId,
					GoodsNum = random.Next(maxNum + 1),
				};
				itemList.Add(backpackItem);
			}
			itemList = itemList.Where(m => m.GoodsNum > 0).ToList();

			if (itemList != null && itemList.Any())
			{
				itemList.ForEach(item =>
				{
					for (int i = 0; i < item.GoodsNum; i++)
					{
						GoodsModel goodsModel = new GoodsModel
						{
							GoodsId = StringHelper.GetGuidStr(),
							BelongsTo = (int)item.enumGoodsBelongsToType,
							GoodsItemId = item.GoodsItemId,
							PlayerId = playerId,
							GoodsPosition = item.GoodsPosition,
							WastageValue = 100,
						};
						goodsList.Add(goodsModel);
					}
				});
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public static void InitAchievements()
		{
			var list = new List<AchievementModel>();
			for (int i = 1; i <= playerNum; i++)
			{
				AchievementModel model = new AchievementModel()
				{
					PlayerId = i,
					AchievementDetailStr = "100000#5#0#0|100200#5#1#0"
				};
				list.Add(model);
			}
			BaseBLL.BatchInsert(list);

		}
	}
}
